package com.enlorenz.core.channel.socket.common.util;

import com.enlorenz.core.channel.common.dstobj.IDstRoute;
import com.enlorenz.core.channel.common.message.LinkConnectedMessage;
import com.enlorenz.core.channel.common.message.LinkDisconnectedMessage;
import com.enlorenz.core.channel.common.message.imp.WriteStatusMessage;
import com.enlorenz.core.channel.socket.common.dstroute.category.NioDstRoute;
import com.enlorenz.core.queue.transfer.MessageQueue;

/**
 * 接收消息操作者
 * 用于操作接收消息的队列
 * @author lcb
 *
 */
public class RecvMessageOperator {
	//接收消息队列
	private MessageQueue recvQueue;
	
	/**
     * 发送链接建立消息
     * @param nioConnObject 链接对象
     */
    public void sendLinkConnMessage(NioDstRoute nioConnObject){
        //放入处理队列
    	sendRecvMessage(createLinkConnMessage(nioConnObject));
    }
    

	/**
     * 创建链接建立消息
     * @param nioConnObject 链接对象
     */
    public LinkConnectedMessage createLinkConnMessage(NioDstRoute nioConnObject){
    	LinkConnectedMessage linkConnectedMessage=new LinkConnectedMessage();
    	linkConnectedMessage.setConnectedKey(nioConnObject);
        return linkConnectedMessage;
    }
    
    
    /**
     * 发送链接关闭消息
     * @param nioConnObject 链接对象
     */
    public void sendLinkDisconnMessage(IDstRoute nioConnObject,Exception ex){
        //放入处理队列
    	sendRecvMessage(createLinkDisconnMessage(nioConnObject, ex));
    }
    
    /**
     * 创建链接关闭消息
     * @param nioConnObject
     * @param ex
     * @return
     */
    public LinkDisconnectedMessage createLinkDisconnMessage(IDstRoute nioConnObject,Exception ex){
    	LinkDisconnectedMessage linkDisconnectedMessage=new LinkDisconnectedMessage();
    	linkDisconnectedMessage.setConnectedKey(nioConnObject);
    	linkDisconnectedMessage.setException(ex);
    	return linkDisconnectedMessage;
    }
	
	
	/**
	 * 发送接收到的消息
	 * @param message 接收到的消息 
	 */
	public void sendRecvMessage(Object message){
		if(null == recvQueue){
			return;
		}
		recvQueue.addMsg(message);
	}
	
	/**
	 * 发送写出状态的消息
	 * @param success	是否成功
	 * @param srcMessage 源消息
	 * @param e 异常
	 */
	public void sendWriteStatusMessage(boolean success,Object srcMessage,Exception e){
		sendRecvMessage(createWriteStatusMessage(success, srcMessage, e));
	}
	
	/**
	 * 创建写出状态的消息
	 * @param success	是否成功
	 * @param srcMessage 源消息
	 * @param e 异常
	 */
	public WriteStatusMessage createWriteStatusMessage(boolean success,Object srcMessage,Exception e){
		WriteStatusMessage writeStatusMessage=new WriteStatusMessage();
		writeStatusMessage.setSuccess(success);
		writeStatusMessage.setSrcMessage(srcMessage);
		writeStatusMessage.setException(e);
		return writeStatusMessage;
	}
	
	/**
	 * 发送写出状态的消息
	 * @param success 是否成功
	 * @param srcMessage 源消息
	 */
	public void sendWriteStatusMessage(boolean success,Object srcMessage){
		sendWriteStatusMessage(success, srcMessage, null);
	}
	
	public void setRecvQueue(MessageQueue recvQueue) {
		this.recvQueue = recvQueue;
	}
}
